<script setup name="Data" lang="ts">
import { DeleteOutlined, FormOutlined } from '@ant-design/icons-vue'
import { parseTime } from '../../../utils/ruoyi.ts'
import useDictStore from '@/stores/modules/dict'
import { optionselect as getDictOptionselect, getType } from '@/api/system/dict/type'
import { addData, delData, getData, listData, updateData } from '@/api/system/dict/data'
import type { DictTypeVO } from '@/api/system/dict/type/types'
import type { DictDataForm, DictDataQuery, DictDataVO } from '@/api/system/dict/data/types'

const message = useMessage()
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const route = useRoute()
const router = useRouter()

const dataList = ref<DictDataVO[]>([])
const loading = ref(true)

const ids = ref<Array<string | number>>([])

const total = ref(0)
const defaultDictType = ref('')
const typeOptions = ref<DictTypeVO[]>([])

const dataFormRef = ref()
const queryFormRef = ref()

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})

// 数据标签回显样式
const listClassOptions = ref<Array<{ value: string, label: string }>>([
  { value: 'default', label: '默认' },
  { value: 'primary', label: '主要' },
  { value: 'success', label: '成功' },
  { value: 'info', label: '信息' },
  { value: 'warning', label: '警告' },
  { value: 'danger', label: '危险' },
])

const initFormData: DictDataForm = {
  dictCode: undefined,
  dictLabel: '',
  dictValue: '',
  cssClass: '',
  listClass: 'default',
  dictSort: 0,
  remark: '',
}
const data = reactive<PageData<DictDataForm, DictDataQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dictName: '',
    dictType: '',
    dictLabel: '',
  },
  rules: {
    dictLabel: [{ required: true, message: '数据标签不能为空', trigger: 'blur' }],
    dictValue: [{ required: true, message: '数据键值不能为空', trigger: 'blur' }],
    dictSort: [{ required: true, message: '数据顺序不能为空', trigger: 'blur' }],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询字典类型详细 */
async function getTypes(dictId: string | number) {
  const { data } = await getType(dictId)
  queryParams.value.dictType = data.dictType
  defaultDictType.value = data.dictType
  getList()
}

/** 查询字典类型列表 */
async function getTypeList() {
  const res = await getDictOptionselect()
  typeOptions.value = res.data
}

/** 查询字典数据列表 */
async function getList() {
  loading.value = true
  const res = await listData(queryParams.value)
  dataList.value = res.rows
  total.value = res.total
  loading.value = false
}

/** 取消按钮 */
function cancel() {
  dialog.visible = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = { ...initFormData }
  dataFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 返回按钮操作 */
function handleClose() {
  router.back()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  queryParams.value.dictType = defaultDictType.value
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  form.value.dictType = queryParams.value.dictType
  dialog.visible = true
  dialog.title = '添加字典数据'
}

/** 修改按钮操作 */
async function handleUpdate(row?: DictDataVO) {
  reset()
  const dictCode = row?.dictCode || ids.value[0]
  const res = await getData(dictCode)
  Object.assign(form.value, res.data)
  dialog.visible = true
  dialog.title = '修改字典数据'
}

/** 提交按钮 */
function submitForm() {
  dataFormRef.value?.validate().then(async () => {
    form.value.dictCode ? await updateData(form.value) : await addData(form.value)
    message.success('操作成功')
    useDictStore().removeDict(queryParams.value.dictType)
    dialog.visible = false
    await getList()
  }).catch()
}

/** 删除按钮操作 */
async function handleDelete(row?: DictDataVO) {
  const dictCodes = row?.dictCode || ids.value
  await proxy?.$modal.confirm(`是否确认删除字典编码为"${dictCodes}"的数据项？`)
  await delData(dictCodes)
  await getList()
  proxy?.$modal.msgSuccess('删除成功')
  useDictStore().removeDict(queryParams.value.dictType)
}

onMounted(() => {
  getTypes(route.params && route.params.dictId as string)
  getTypeList()
})
</script>

<template>
  <div class="p-2">
    <a-card shadow="hover">
      <template #title>
        <div class="flex flex-between">
          <div>
            <a-form ref="queryFormRef" class="inline-form" :model="queryParams" layout="inline" label-width="68px">
              <a-form-item label="字典名称" prop="dictType">
                <a-select v-model:value="queryParams.dictType" style="width: 200px">
                  <a-select-option v-for="item in typeOptions" :key="item.dictId" :label="item.dictName" :value="item.dictType">
                    {{ item.dictName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="字典标签" prop="dictLabel">
                <a-input
                  v-model:value="queryParams.dictLabel" placeholder="请输入字典标签" clearable style="width: 200px"
                  @keyup.enter="handleQuery"
                />
              </a-form-item>
              <a-form-item>
                <a-button type="primary" class="mr-10px" @click="handleQuery">
                  搜索
                </a-button>
                <a-button @click="resetQuery">
                  重置
                </a-button>
              </a-form-item>
            </a-form>
          </div>
          <div>
            <a-row :gutter="10">
              <a-col>
                <a-button v-hasPermi="['system:dict:add']" type="primary" @click="handleAdd">
                  新增
                </a-button>
              </a-col>
              <a-col>
                <a-button plain @click="handleClose">
                  关闭
                </a-button>
              </a-col>
            </a-row>
          </div>
        </div>
      </template>

      <a-table :loading="loading" :pagination="false" :data-source="dataList">
        <a-table-column title="字典标签" data-index="dictLabel">
          <template #default="{ record }">
            <span
              v-if="(record.listClass === '' || record.listClass === 'default') && (record.cssClass === '' || record.cssClass == null)"
            >{{
              record.dictLabel
            }}</span>
            <a-tag
              v-else
              :type="(record.listClass === 'primary' || record.listClass === 'default') ? '' : record.listClass"
              :class="record.cssClass"
            >
              {{ record.dictLabel }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="字典键值" align="center" data-index="dictValue" />
        <a-table-column title="字典排序" align="center" data-index="dictSort" />
        <a-table-column title="备注" align="center" data-index="remark" :ellipsis="true" />
        <a-table-column title="创建时间" align="center" data-index="createTime" width="180">
          <template #default="{ record }">
            <span>{{ parseTime(record.createTime) }}</span>
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template #default="{ record }">
            <a-tooltip content="修改" placement="top">
              <a-button v-hasPermi="['system:dict:edit']" type="link" @click="handleUpdate(record)">
                <FormOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip content="删除" placement="top">
              <a-button v-hasPermi="['system:dict:remove']" type="link" icon="" @click="handleDelete(record)">
                <DeleteOutlined />
              </a-button>
            </a-tooltip>
          </template>
        </a-table-column>
      </a-table>

      <div class="text-right mt-5">
        <a-pagination
          v-show="total > 0"
          v-model:current="queryParams.pageNum" v-model:pageSize="queryParams.pageSize" :total="total"
          show-less-items @change="getList"
        />
      </div>
    </a-card>
    <!-- 添加或修改参数配置对话框 -->
    <a-modal v-model:open="dialog.visible" :mask-closable="false" :keyboard="false" :title="dialog.title" width="500px" append-to-body>
      <a-form ref="dataFormRef" :model="form" :rules="rules" :label-col="{ style: 'width:80px' }">
        <a-form-item label="字典类型">
          <a-input v-model:value="form.dictType" :disabled="true" />
        </a-form-item>
        <a-form-item label="数据标签" prop="dictLabel">
          <a-input v-model:value="form.dictLabel" placeholder="请输入数据标签" />
        </a-form-item>
        <a-form-item label="数据键值" prop="dictValue">
          <a-input v-model:value="form.dictValue" placeholder="请输入数据键值" />
        </a-form-item>
        <a-form-item label="样式属性" prop="cssClass">
          <a-input v-model:value="form.cssClass" placeholder="请输入样式属性" />
        </a-form-item>
        <a-form-item label="显示排序" prop="dictSort">
          <a-input-number v-model:value="form.dictSort" :controls="false" controls-position="right" :min="0" />
        </a-form-item>
        <a-form-item label="回显样式" prop="listClass">
          <a-select v-model:value="form.listClass">
            <a-select-option
              v-for="item in listClassOptions"
              :key="item.value"
              :label="`${item.label}(${item.value})`"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="备注" prop="remark">
          <a-textarea v-model:value="form.remark" placeholder="请输入内容" />
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button @click="cancel">
            取 消
          </a-button>

          <a-button type="primary" @click="submitForm">
            确 定
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>
